
#include <sstream>
#include "MysqlStorage.h"
#include "define.h"
#include <mqPool.h>
#include <viva.h>
#include "Debug.h"
//#include "DataUtils.h"
using namespace std;

bool MySQLStorage :: Initialize(const char *conf) 
{
 DEBUG2("MqPool::Instance ", conf );
	MqPool *pA =   MqPool::Instance(conf); 	
	if(pA == NULL)
        {
                ERRO <<" MqPool Instance error" << endl;
		return false;
        } 
	else
	{
/*
DEBUG1("start to check MySQL");
		int fc = pA->GetFarmsCounts();
		for(int i=0; i<fc; i++)
		{
			MYSQL* rcon = pA->GetReader(i);
			if(rcon == NULL)
                        {
                                cerr<<"Get reader by farmid="<< i<<", but return is NULL" << endl;
				return false;
                        } 
		}
*/
		GKeyFile *kv = g_key_file_new();
		GError *err = NULL;
		if(TRUE != g_key_file_load_from_file(kv,conf, G_KEY_FILE_NONE , &err))
		{
			if (err != NULL)
			{
				cerr << "Unable to read file:" << err->message << endl;
				g_error_free (err);
			}
			g_key_file_free(kv);
			return false;
		}

		gchar *pval =  g_key_file_get_value(kv,"global", "writedb",  NULL);
		if(pval == NULL)
		{
			ERRO<<"needn't write to db!"<< endl;
			m_bWrite2DB = false;
		}
		else
		{
			atoi((char *)pval) > 0 ? m_bWrite2DB = true: m_bWrite2DB = false; 
			g_free(pval);
		}
		pval =  g_key_file_get_value(kv,"global", "txlog",  NULL);
		if(pval == NULL)
		{
			cerr<<"no txlog in global"<< endl;
                        m_pTx = NULL;
		}
		else
		{ 
			string txconf = pval;
			g_free(pval);
			g_key_file_free(kv);
			m_pTx = new  Viva();
			if(!m_pTx->Initilize(txconf.c_str()))
			{
				delete m_pTx;
                                m_pTx = NULL;
				return false;
			} 
		}  
                DEBUG1("GREAT!!!!!!!!, Object initialize OK "); 
		return true;
	}
}


int MySQLStorage :: Read(int ihash, GHashTable *kv, char **wbuf, unsigned &wsize, unsigned &wbytes)
{
	DEBUG1("DO");
	return 0;
}

int MySQLStorage :: Write(int ihash, GHashTable *kv)
{
	DEBUG1("DO");
	return 0;
}


int MySQLStorage :: Atom(int ihash, GHashTable *kv, char **wbuf, unsigned &wsize, unsigned &wbytes)
{
	DEBUG1("DO");
	return 0;
}


int MySQLStorage :: Delete(int ihash, GHashTable *kv)
{
	DEBUG1("DO");
	return 0;
}


extern "C" IStorage * create_storage(const char *config) {
	IStorage *obj = new MySQLStorage();
	if(obj->Initialize(config))
		return obj;
	delete obj;
	return NULL; 
}

extern "C" void destroy_storage(MySQLStorage *obj) {
		if(obj != NULL)
			delete obj;
		obj = NULL;
}

